package com.atguigu.cloud.service.impl;

import com.atguigu.cloud.api.AccountFeignApi;
import com.atguigu.cloud.api.StorageFeignApi;
import com.atguigu.cloud.entities.Order;
import com.atguigu.cloud.mapper.OrderMapper;
import com.atguigu.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 下订单,减库存,减余额
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private StorageFeignApi storageFeignApi;
    @Resource
    private AccountFeignApi accountFeignApi;

    @GlobalTransactional(name = "leo-create-order",rollbackFor = Exception.class)
    public void create(Order order){

        //xid检查
        String xid = RootContext.getXID();

        //创建订单
        log.info("创建订单,xid_order:"+xid);

        order.setStatus(0);

        int result = orderMapper.insertSelective(order);
        Order orderFromDB = null;

        if(result > 0){
            orderFromDB = orderMapper.selectOne(order);
            log.info("订单创建成功,orderFromDB info:" + orderFromDB);

            log.info("开始减扣库存");
            storageFeignApi.decrease(orderFromDB.getProductId(),orderFromDB.getCount());
            log.info("减扣库存成功");

            log.info("开始扣减余额");
            accountFeignApi.decrease(orderFromDB.getUserId(),orderFromDB.getMoney());
            log.info("扣减余额成功");

            orderFromDB.setStatus(1);
            int updateResult = orderMapper.updateByPrimaryKeySelective(orderFromDB);

            log.info("订单状态修改完成:" + updateResult);
            log.info("orderFromDb:"+orderFromDB);
        }

        log.info("创建订单结束,xid_order:"+xid);
    }
}
